package org.e_gold.dao.impl;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.e_gold.dao.ContractDAO;
import org.e_gold.model.Contract;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository
public class ContractDAOImpl extends AbstractGenericDAO<Contract> implements ContractDAO {

	private static final Logger logger = Logger.getLogger(ContractDAOImpl.class);

	public ContractDAOImpl() {

		super(Contract.class);
	}

	@Override
	@Transactional
	public Contract findByEventIdAndContractType(Long eventId, String contractType) {

		Contract retval = null;
		try {
			retval = (Contract) getCurrentSession().
					getNamedQuery("findByEventIdAndContractType")
					.setString("contractType", contractType)
					.setLong("eventId", eventId)
					.uniqueResult();
		} catch (Exception e) {
			logger.error("Error findByEventIdAndContractType : " + eventId + "  contractType : " + contractType);
			logger.error(e);
		}
		return retval;
	}

	@Override
	@Transactional
	public Contract getRunningContract() {

		Contract retval = null;
		Criteria criteria = getCurrentSession().createCriteria(Contract.class);
		criteria.setFirstResult(0);
		// criteria.add(Restrictions.eq(Contract., value));
		if (CollectionUtils.isNotEmpty(criteria.list())) {
			retval = (Contract) criteria.list().get(0);
		}
		return retval;
	}

	@Override
	@Transactional
	public void updateFalseQualify() {

		getCurrentSession().createSQLQuery(UPDATE_ALL_CONTRACT_QUALIFY_TO_FALSE).executeUpdate();
	}

	@Override
	@Transactional
	public void updateFalseQualifyContract(String strIdList) {
		try{

			String SQLCountryStatusToFalse = UPDATE_CONTRACT_QUALIFY_TO_FALSE.replace("idList", strIdList);
			Query q = getCurrentSession().createSQLQuery(SQLCountryStatusToFalse);
			q.executeUpdate();
		}catch(Exception ex){
			ex.printStackTrace();
			logger.error(ex);
		}
	}

}
